class Solution {
public:
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    int swimInWater(vector<vector<int>>& grid) {
        int t = 0, n = grid.size();
        priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq;
        pq.push({ grid[0][0], 0, 0 });
        vector<vector<bool>> arr(n, vector<bool>(n, false));
        while (true) {
            auto e = pq.top();
            pq.pop();
            int val = get<0>(e), x = get<1>(e), y = get<2>(e);
            arr[x][y] = true;
            t = max(t, val);
            if (x == n - 1 && y == n - 1) break;
            for (int k = 0; k < 4; k++) {
                int a = x + dx[k], b = y + dy[k];
                if (a >= 0 && a < n && b >= 0 && b < n && arr[a][b] == false) pq.push({ grid[a][b], a, b });
            }
        }
        return t;
    }
};